package com.leff.cards.web;

import android.util.Log;

import com.leff.cards.data.ResponseCard;
import com.leff.cards.util.Secrets;
import com.leff.cards.util.Dictionary;

public abstract class WebRequest implements Secrets {

	private static final String COMMAND = "cmd";
	
	private WebCommand mCommand;
	protected final Dictionary mParameters;
	
	public WebRequest(WebCommand command) {
		mCommand = command;
		mParameters = new Dictionary();
		mParameters.put(COMMAND, mCommand.name());
	}
	
	public Dictionary getParameters() {
		return mParameters;
	}
	
	public String getCommandName() {
		return mCommand.name();
	}

	public void handleResponse(Dictionary response) {
		
		Long error = (Long)response.get("err");
		Object result = response.get("res");
		
		if(error > 0) {
			onSuccess(result);
		} else {
			onFailure(result);
		}
	}
	
	@Override
	public boolean equals(Object O) {
		if(!(O instanceof WebRequest)) {
			return false;
		}
		WebRequest WR = (WebRequest)O;
		return mCommand.equals(WR.getCommandName());
	}
	
	public enum WebCommand {
		LOGIN,
		GET_GROUPS,
		SUBMIT_CARD,
		SELECT_CARD,
		UPDATE_USER,
		CREATE_GROUP,
		LEAVE_GROUP,
		GET_INVITES,
		INVITE_USER,
		INVITE_RESPONSE,
		REGISTER_DEVICE,
		UNREGISTER_DEVICE,
	}
	
	private void onSuccess(Object json) {
		Log.v(TAG, getCommandName() + ": " + json);
		
		Dictionary result = Dictionary.fromJSONObject(json);
		parseResultDictionary(result);
	}
	private void onFailure(Object json) {
		
		Dictionary result = Dictionary.fromJSONObject(json);
		String message = (String)result.get("reason");
		
		Log.v(TAG, getCommandName() + " Failure: " + message);
	}
	
	protected abstract void parseResultDictionary(Dictionary dict);
	
	public static String encodeCards(ResponseCard[] cards) {

		StringBuilder sb = new StringBuilder();
		for(ResponseCard rc : cards) {
			sb.append(rc.getId()).append(",");
		}
		sb.deleteCharAt(sb.length() - 1);
		return sb.toString();
	}
	
	public class Parameter {
		public static final String ID = "id";
		public static final String NAME = "name";
		public static final String FB_ID = "fbid";
		public static final String GROUP_ID = "group_id";
		public static final String JOIN = "join";
		public static final String CARD_IDS = "card_ids";
		public static final String GCM_ID = "gcm_id";
	}
}
